import os
import re
import matplotlib.pyplot as plt


def save_image_file(sorted_data, save_path, figure):
    # 提取文件信息
    title = sorted_data.get('title', 'unknown_title')
    book_id = sorted_data.get('book_id', 'unknown_book')
    page_id = sorted_data.get('page_id', 'unknown_page')

    # 创建文件夹路径（移除可能 invalid 的字符）
    safe_title = re.sub(r'[<>:"/\\|?*]', '_', title)  # 移除文件名非法字符
    folder_path = os.path.join(save_path, safe_title) + '\image_file'
    print(folder_path)

    # 创建文件夹（如果不存在）
    os.makedirs(folder_path, exist_ok=True)

    # 创建文件名
    file_name = f"{book_id}_{page_id}.png"
    save_image_path = os.path.join(folder_path, file_name)

    # 保存image文件
    if figure is not None:
        figure.savefig(save_image_path, dpi=300, bbox_inches='tight')
        plt.close(figure)

    print(f'排序后的image已保存到: {save_image_path}')
    return save_image_path
